﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Configuration;
using System.IO;
using System.Net.Sockets;
using System.Net;
using System.Text.RegularExpressions;

namespace _2QWebProxy.App_Code
{

    public class Utils
    {
        static Regex cookieRegEx = new Regex(@",(?! )");
        static String[] colonSpaceSplit = new string[] { ": " };
        static char[] semiSplit = new char[] { ';' };
        #region Header

        public static string GetHeader(Socket socket, out byte[] arrByte)
        {
            string header = "";
            int i = 0;
            arrByte = new byte[65535];
            while (true)
            {
                byte[] bytes = new byte[1];
                int bytesRec = socket.Receive(bytes);
                header += System.Text.Encoding.ASCII.GetString(bytes, 0, bytesRec);
                arrByte[i] = bytes[0];
                i++;
                if (header.IndexOf("\r\n\r\n") > -1 || header.IndexOf("\n\n") > -1)
                {
                    break;
                }
            }
            Array.Resize(ref arrByte, i);
            return header;
        }

        public static string FilterHeader(string header, string filterString)
        {
            string host = "";
            string[] headers = header.Split(new char[] { '\n' });
            //string[] requestLineElements = requestLine.Split(new char[] { ' ' });
            for (int i = 1; i < headers.Length; ++i)
            {
                string[] hElem = headers[i].Split(new char[] { ':' });
                if (hElem.Length >= 2)
                {
                    if (hElem[0].Trim().ToLower().Equals(filterString.ToLower()))
                    {
                        host = hElem[1].Trim();
                    }
                }
            }
            return host;
        }

        public static List<Tuple<String, String>> ProcessResponse(string response)
        {
            String value = null;
            String header = null;
            List<Tuple<String, String>> returnHeaders = new List<Tuple<String, String>>();
            string[] list = Regex.Split(response, "\r\n");
            foreach (String s in list)
            {
                string[] headers = s.Split(colonSpaceSplit, 2, StringSplitOptions.None);
                if (headers[0].ToLower() == "set-cookie")
                {
                    header = headers[0];
                    value = headers[1];
                }
                else
                    returnHeaders.Add(new Tuple<String, String>(headers[0], headers[1]));
            }

            if (!String.IsNullOrWhiteSpace(value))
            {
                String[] cookies = cookieRegEx.Split(value);
                foreach (String cookie in cookies)
                    returnHeaders.Add(new Tuple<String, String>("Set-Cookie", cookie));

            }
            return returnHeaders;
        }

        public static string BuildResponseStatus(int code, String description)
        {
            return String.Format("HTTP/1.0 {0} {1}", code, description);
        }

        public static string BuildResponseHeaders(List<Tuple<String, String>> headers)
        {
            String str = String.Empty;
            if (headers != null)
            {
                foreach (Tuple<String, String> header in headers)
                    str += String.Format("{0}: {1}", header.Item1, header.Item2) + "\r\n";
            }
            str += "\r\n";
            return str;
        }

        public static int ReadReponseHeaders(string responseHeader, out List<Tuple<String, String>> response)
        {
            int contentLen = 0;
            response = new List<Tuple<string, string>>();
            String[] headers = Regex.Split(responseHeader, "\r\n");
            string[] responeLine = headers[0].Split(' ');
            response.Add(new Tuple<String, String>("Status-Code", responeLine[1]));
            response.Add(new Tuple<String, String>("Status-Description", responeLine[2]));
            for (int i = 1; i < headers.Count(); i++)
            {
                var item = headers[i];
                String[] header = item.Split(colonSpaceSplit, 2, StringSplitOptions.None);
                switch (header[0].ToLower())
                {
                    case "content-type":
                        response.Add(new Tuple<String, String>(header[0], header[1]));
                        break;
                    case "content-length":
                        int.TryParse(header[1], out contentLen);
                        break;
                    default:
                        try
                        {
                            response.Add(new Tuple<String, String>(header[0], header[1]));
                        }
                        catch
                        {
                        }
                        break;
                }
            }
            return contentLen;
        }

        public static int ReadRequestHeaders(string requestHeader, out List<Tuple<String, String>> request)
        {
            int contentLen = 0;
            String[] headers = Regex.Split(requestHeader, "\r\n");
            request = new List<Tuple<string, string>>();
            foreach (string item in headers)
            {
                String[] header = item.Split(colonSpaceSplit, 2, StringSplitOptions.None);
                switch (header[0].ToLower())
                {
                    case "host":
                    case "user-agent":
                    case "accept":
                    case "referer":
                    case "cookie":
                    case "content-type":
                        request.Add(new Tuple<String, String>(header[0], header[1]));
                        break;
                    case "proxy-connection":
                    case "connection":
                    case "keep-alive":
                        //ignore these
                        break;
                    case "content-length":
                        int.TryParse(header[1], out contentLen);
                        break;
                    case "if-modified-since":
                        String[] sb = header[1].Trim().Split(semiSplit);
                        DateTime d;
                        if (DateTime.TryParse(sb[0], out d))
                            request.Add(new Tuple<String, String>(header[0], header[1]));
                        break;
                    default:
                        try
                        {
                            request.Add(new Tuple<String, String>(header[0], header[1]));
                        }
                        catch
                        {
                        }
                        break;
                }
            }
            return contentLen;
        }

        #endregion

        #region Privacy Domain

        public static List<PrivacyDomain> GetPrivacyDomain(string status = null)
        {
            XDocument data = XDocument.Load(ConfigurationManager.AppSettings["ListDomainIPType"]);

            var privacyDomain = (from c in data.Descendants("domain")
                                 where status == null || c.Attribute("status").Value.Equals(status)
                                 select new PrivacyDomain()
                                 {
                                     Name = c.Value,
                                     Status = c.Attribute("status").Value
                                 });
            return privacyDomain.ToList();
        }

        public static void SavePrivacyDomain(PrivacyDomain domain)
        {
            XDocument data = XDocument.Load(ConfigurationManager.AppSettings["ListDomainIPType"]);
            XElement privacyDomain = data.Descendants("domain").Where(c => c.Value.Equals(domain.Name)).FirstOrDefault();

            if (privacyDomain != null)
            {
                privacyDomain.SetAttributeValue("status", domain.Status);
                privacyDomain.SetValue(domain.Name);
            }
            else
            {
                privacyDomain = new XElement("domain", domain.Name);
                privacyDomain.SetAttributeValue("status", domain.Status);

                XElement item = new XElement("domains");
                item.Add(privacyDomain);
                data.Element("accesscontrols").Add(item);
            }

            data.Save(ConfigurationManager.AppSettings["ListDomainIPType"]);
        }

        public static void DeletePrivacyDomain(PrivacyDomain domain)
        {
            XDocument data = XDocument.Load(ConfigurationManager.AppSettings["ListDomainIPType"]);

            XElement privacyDomain = data.Descendants("domains").Where(c => c.Value.Equals(domain.Name)).FirstOrDefault();
            if (privacyDomain != null)
            {
                privacyDomain.Remove();
                data.Save(ConfigurationManager.AppSettings["ListDomainIPType"]);
            }
        }

        public static void DeleteAllPrivacyDomain()
        {
            XDocument data = XDocument.Load(ConfigurationManager.AppSettings["ListDomainIPType"]);

            var privacyDomain = data.Descendants("domains");
            if (privacyDomain != null)
            {
                privacyDomain.Remove();
                data.Save(ConfigurationManager.AppSettings["ListDomainIPType"]);
            }
        }

        public static bool IsDomain(string domainName, string status)
        {
            List<PrivacyDomain> domains = GetPrivacyDomain(status);
            foreach (PrivacyDomain oDomain in domains)
            {
                if (oDomain.Name.Equals(domainName))
                    return true;
            }
            return false;
        }

        #endregion

        #region Privacy IPAddress

        public static List<PrivacyIpAddress> GetPrivacyIPAddress(string status = null)
        {
            XDocument data = XDocument.Load(ConfigurationManager.AppSettings["ListDomainIPType"]);

            var privacyIPAddress = (from c in data.Descendants("ipaddress")
                                    where status == null || c.Attribute("status").Value.Equals(status)
                                    select new PrivacyIpAddress()
                                    {
                                        Name = c.Value,
                                        Status = c.Attribute("status").Value
                                    });
            return privacyIPAddress.ToList();
        }

        public static void SaveIPAddress(PrivacyIpAddress ipAddress)
        {
            XDocument data = XDocument.Load(ConfigurationManager.AppSettings["ListDomainIPType"]);
            XElement privacyIPAddress = data.Descendants("ipaddress").Where(c => c.Value.Equals(ipAddress.Name)).FirstOrDefault();
            if (privacyIPAddress != null)
            {
                privacyIPAddress.SetAttributeValue("status", ipAddress.Status);
                privacyIPAddress.SetValue(ipAddress.Name);
            }
            else
            {
                privacyIPAddress = new XElement("ipaddress", ipAddress.Name);
                privacyIPAddress.SetAttributeValue("status", ipAddress.Status);

                XElement item = new XElement("ipaddresses");
                item.Add(privacyIPAddress);
                data.Element("accesscontrols").Add(item);
            }
            data.Save(ConfigurationManager.AppSettings["ListDomainIPType"]);
        }

        public static bool IsIPAddress(string ipAddress, string status)
        {
            List<PrivacyIpAddress> ipAddresses = GetPrivacyIPAddress(status);
            foreach (PrivacyIpAddress oIPAddress in ipAddresses)
            {
                if (oIPAddress.Name.Equals(ipAddress))
                    return true;

            }
            return false;
        }

        public static void DeletePrivacyIPAddress(PrivacyIpAddress ipAddress)
        {
            XDocument data = XDocument.Load(ConfigurationManager.AppSettings["ListDomainIPType"]);

            XElement privacyIPAddress = data.Descendants("ipaddresses").Where(c => c.Value.Equals(ipAddress.Name)).FirstOrDefault();
            if (privacyIPAddress != null)
            {
                privacyIPAddress.Remove();
                data.Save(ConfigurationManager.AppSettings["ListDomainIPType"]);
            }
        }

        public static void DeleteAllPrivacyIPAddress()
        {
            XDocument data = XDocument.Load(ConfigurationManager.AppSettings["ListDomainIPType"]);

            var privacyIPAddress = data.Descendants("ipaddresses");
            if (privacyIPAddress != null)
            {
                privacyIPAddress.Remove();
                data.Save(ConfigurationManager.AppSettings["ListDomainIPType"]);
            }
        }

        #endregion

        #region Privacy File

        public static List<PrivacyFile> GetPrivacyFile(string status = null)
        {
            XDocument data = XDocument.Load(ConfigurationManager.AppSettings["ListDomainIPType"]);

            var privacyFile = (from c in data.Descendants("files")
                               where status == null || c.Element("file").Attribute("status").Value.Equals(status)
                               select new PrivacyFile()
                                    {
                                        Type = c.Element("file").Value,
                                        Status = c.Element("file").Attribute("status").Value
                                    });
            return privacyFile.ToList();
        }


        public static void SavePrivacyFile(PrivacyFile file)
        {
            XDocument data = XDocument.Load(ConfigurationManager.AppSettings["ListDomainIPType"]);

            XElement privacyFile = data.Descendants("files").Elements("file").Where(c => c.Value.Equals(file.Type)).FirstOrDefault();
            if (privacyFile != null)
            {
                privacyFile.SetAttributeValue("status", file.Status);
                privacyFile.SetValue(file.Type);
            }
            else
            {
                privacyFile = new XElement("file", file.Type);
                privacyFile.SetAttributeValue("status", file.Status);

                XElement item = new XElement("files");
                item.Add(privacyFile);
                data.Element("accesscontrols").Add(item);
            }
            data.Save(ConfigurationManager.AppSettings["ListDomainIPType"]);
            //XElement privacyFile = data.Descendants("file").Where(c => c.Value.Equals(file.Type)).FirstOrDefault();
            //if (privacyFile != null)
            //{
            //    privacyFile.SetAttributeValue("status", file.Status);
            //    privacyFile.SetValue(file.Type);
            //}
            //else
            //{
            //    privacyFile = new XElement("file", file.Type);
            //    privacyFile.SetAttributeValue("status", file.Status);

            //    XElement item = new XElement("files");
            //    item.Add(privacyFile);
            //    data.Element("accesscontrols").Add(item);
            //}
            //data.Save(ConfigurationManager.AppSettings["ListDomainIPType"]);
        }

        public static void DeletePrivacyFile(PrivacyFile file)
        {
            XDocument data = XDocument.Load(ConfigurationManager.AppSettings["ListDomainIPType"]);

            XElement privacyFile = data.Descendants("files").Where(c => c.Value.Equals(file.Type)).FirstOrDefault();
            if (privacyFile != null)
            {
                privacyFile.Remove();
                data.Save(ConfigurationManager.AppSettings["ListDomainIPType"]);
            }
        }


        public static void DeleteAllPrivacyFile()
        {
            XDocument data = XDocument.Load(ConfigurationManager.AppSettings["ListDomainIPType"]);

            var privacyTypes = data.Descendants("files");
            if (privacyTypes != null)
            {
                privacyTypes.Remove();
                data.Save(ConfigurationManager.AppSettings["ListDomainIPType"]);
            }
        }

        public static bool IsFile(string fileType, string status)
        {
            if (fileType != null)
            {
                List<PrivacyFile> files = GetPrivacyFile(status);
                foreach (PrivacyFile oFile in files)
                {
                    if (fileType.Contains(oFile.Type))
                        return true;
                }

            }
            return false;
        }

        #endregion

        #region Port List

        public static List<Port> GetPortList()
        {
            XDocument data = XDocument.Load(ConfigurationManager.AppSettings["PortData"]);

            var ports = (from c in data.Descendants("port")
                         select new Port()
                         {
                             PortNumber = Int32.Parse(c.Value)
                         });
            return ports.ToList();
        }

        public static void SavePortList(int port)
        {
            XDocument data = XDocument.Load(ConfigurationManager.AppSettings["PortData"]);
            var portList = data.Descendants("Ports");
            var list = (from p in portList.Elements("port") where p.Value.Equals(port.ToString()) select p).FirstOrDefault();
            if (list != null)
            {
                list.SetValue(port);
            }
            else
            {
                list = new XElement("port", port);

                data.Element("Ports").Add(list);
            }

            data.Save(ConfigurationManager.AppSettings["PortData"]);
        }

        public static void DeletePort(int port)
        {
            XDocument data = XDocument.Load(ConfigurationManager.AppSettings["PortData"]);

            XElement oPort = data.Descendants("port").Where(c => c.Value.Equals(port.ToString())).FirstOrDefault();
            if (oPort != null)
            {
                oPort.Remove();
                data.Save(ConfigurationManager.AppSettings["PortData"]);
            }
        }

        public static void DeleteAllPort()
        {
            XDocument data = XDocument.Load(ConfigurationManager.AppSettings["PortData"]);

            var portList = data.Descendants("port");
            if (portList != null)
            {
                portList.Remove();
                data.Save(ConfigurationManager.AppSettings["PortData"]);
            }
        }

        #endregion

        #region File Types

        public static List<string> GetCommonFileType()
        {
            XDocument data = XDocument.Load(ConfigurationManager.AppSettings["ListCommonFileType"]);

            var types = (from c in data.Descendants("type") select c.Value);
            return types.ToList();
        }

        #endregion

        #region Privacy Domain Type

        public static string BuildListFileTypeDomain(string domain)
        {
            string str = string.Empty;
            List<PrivacyFile> list = GetFileTypesDomain(domain);
            foreach (PrivacyFile file in list)
            {
                str += file.Type + "; q=0,";
            }
            return str;
        }

        public static string BuildListFileTypeIPAddress(string domain)
        {
            string str = string.Empty;
            List<PrivacyFile> list = GetFileTypesIPAddress(domain);
            foreach (PrivacyFile file in list)
            {
                str += file.Type + "; q=0,";
            }
            return str;
        }

        public static string BuildListFileType()
        {
            string str = string.Empty;
            List<PrivacyFile> list = GetFileTypes();
            foreach (PrivacyFile file in list)
            {
                str += file.Type + "; q=0,";
            }
            return str;
        }

        public static List<PrivacyFile> GetFileTypes()
        {
            XDocument data = XDocument.Load(ConfigurationManager.AppSettings["ListDomainIPType"]);

            var privacyFile = (from c in data.Descendants("files")
                               where c.Element("file").Attribute("status").Value.Equals("deny")
                               select new PrivacyFile()
                               {
                                   Type = c.Element("file").Value,
                                   Status = c.Element("file").Attribute("status").Value
                               });
            return privacyFile.ToList();
        }

        public static List<PrivacyFile> GetFileTypesDomain(string domain)
        {
            XDocument data = XDocument.Load(ConfigurationManager.AppSettings["ListDomainIPType"]);

            var privacyFile = (from c in data.Descendants("domains")
                               where c.Element("domain").Value.Equals(domain) && c.Element("file").Attribute("status").Value.Equals("deny")
                               select new PrivacyFile()
                               {
                                   Type = c.Element("file").Value,
                                   Status = c.Element("file").Attribute("status").Value
                               });
            return privacyFile.ToList();
        }

        public static List<PrivacyFile> GetFileTypesIPAddress(string ipAddress)
        {
            XDocument data = XDocument.Load(ConfigurationManager.AppSettings["ListDomainIPType"]);

            var privacyFile = (from c in data.Descendants("ipaddresses")
                               where c.Element("ipaddress").Value.Equals(ipAddress) && c.Element("file").Attribute("status").Value.Equals("deny")
                               select new PrivacyFile()
                               {
                                   Type = c.Element("file").Value,
                                   Status = c.Element("file").Attribute("status").Value
                               });
            return privacyFile.ToList();
        }


        public static bool IsDomainDenyFileType(string domainName, string fileType)
        {
            if (fileType != null)
            {
                XDocument data = XDocument.Load(ConfigurationManager.AppSettings["ListDomainIPType"]);

                var privacyDomain = (from c in data.Descendants("domains") where c.Element("domain").Value.Equals(domainName) select c).FirstOrDefault();

                if (privacyDomain != null)
                {
                    var file = (from f in privacyDomain.Elements("file") where fileType.Contains(f.Value) select f).FirstOrDefault();
                    if (file != null)
                    {
                        if (file.Attribute("status").Value.Equals("deny"))
                            return false;
                    }
                }
            }
            return true;
        }

        public static bool IsIPAddressDenyFileType(string ipAddress, string fileType)
        {
            if (IsIPAddress(ipAddress, "allow"))
            {
                XDocument data = XDocument.Load(ConfigurationManager.AppSettings["ListDomainIPType"]);

                var privacyIPAddress = (from c in data.Descendants("ipaddresses") where c.Element("ipaddress").Value.Equals(ipAddress) select c).FirstOrDefault();
                if (privacyIPAddress != null)
                {
                    var file = (from f in privacyIPAddress.Elements("file") where f.Value.Equals(fileType) select f).FirstOrDefault();
                    if (file != null)
                    {
                        if (file.Attribute("status").Value.Equals("deny")) return false;
                    }
                }
            }
            else
            {
                return false;
            }
            return true;
        }

        public static List<int> SortPriorityRule()
        {
            List<int> newList = new List<int>(GlobalVariables.listPriorityRule);
            for (int i = 0; i < newList.Count - 1; i++)
            {
                for (int j = i + 1; j < newList.Count; j++)
                {
                    if (newList[i] > newList[j])
                    {
                        int temp = newList[i];
                        newList[i] = newList[j];
                        newList[j] = temp;
                    }
                }
            }
            return newList;
        }

        public static List<int> FindPriorityRule(List<int> listPriorityRule)
        {
            List<int> newList = new List<int>(listPriorityRule.Count);
            for (int i = 0; i < listPriorityRule.Count; i++)
            {
                for (int j = 0; j < GlobalVariables.listPriorityRule.Count; j++)
                {
                    if (GlobalVariables.listPriorityRule[i] == listPriorityRule[j] && !newList.Contains(j))
                    {
                        newList.Add(j);
                        break;
                    }
                }
            }
            return newList;
        }

        public static bool CheckRules(string domainName = null, string ipAddress = null, string contentType = null, int ruleType = 0)
        {
            bool flag = true;
            List<int> listPriorityRule = SortPriorityRule();
            listPriorityRule = FindPriorityRule(listPriorityRule);
            for (int i = 0; i < listPriorityRule.Count(); i++)
            {
                switch (listPriorityRule[i])
                {
                    case (int)GlobalVariables.RuleType.DenyWebsite:
                        if (Properties.Settings.Default.isDenyWebsite)
                        {
                            flag = !IsDomain(domainName, "deny");
                            return flag;
                        }
                        break;
                    case (int)GlobalVariables.RuleType.AllowWebsite:
                        if (Properties.Settings.Default.isAllowWebsite)
                        {
                            flag = IsDomain(domainName, "allow");
                            return flag;
                        }
                        break;
                    case (int)GlobalVariables.RuleType.DenyIPAddress:
                        if (Properties.Settings.Default.isDenyIPAddress)
                        {
                            flag = !IsIPAddress(ipAddress, "deny");
                            return flag;
                        }
                        break;
                    case (int)GlobalVariables.RuleType.AllowIPAddress:
                        if (Properties.Settings.Default.isAllowIPAddress)
                        {
                            flag = IsIPAddress(ipAddress, "allow");
                            return flag;
                        }
                        break;
                    case (int)GlobalVariables.RuleType.DenyFileType:
                        if (Properties.Settings.Default.isDenyFileType)
                        {
                            flag = !IsFile(contentType, "deny");
                            return flag;
                        }
                        break;
                    case (int)GlobalVariables.RuleType.AllowFileType:

                        //flag = IsFile(contentType, "allow");
                        break;
                    case (int)GlobalVariables.RuleType.DenyDomainFileType:
                        if (Properties.Settings.Default.isWebsiteDenyFileType)
                        {
                            flag = IsDomainDenyFileType(domainName, contentType);
                            return flag;
                        }
                        break;
                    case (int)GlobalVariables.RuleType.DenyIPAddressFileType:
                        if (Properties.Settings.Default.isIPAddressDenyFileType)
                        {
                            flag = IsIPAddressDenyFileType(ipAddress, contentType);
                            return flag;
                        }
                        break;
                    default:
                        flag = true;
                        break;
                }
            }
            return flag;
        }

        #endregion

        #region List Deny File Type

        public static List<DenyFileType> GetListWebsiteDenyFileType()
        {
            XDocument data = XDocument.Load(ConfigurationManager.AppSettings["ListDomainIPType"]);

            var list = (from c in data.Descendants("domains")
                        where c.Element("domain").Attribute("status").Value.Equals("allow")
                        select new DenyFileType()
                        {
                            Name = c.Element("domain").Value,
                            FileTypes = (from f in c.Elements("file") where f.Attribute("status").Value.Equals("deny") select f.Value).ToList()
                        });
            return list.ToList();
        }

        public static List<DenyFileType> GetListIPAddressDenyFileType()
        {
            XDocument data = XDocument.Load(ConfigurationManager.AppSettings["ListDomainIPType"]);

            var list = (from c in data.Descendants("ipaddresses")
                        where c.Element("ipaddress").Attribute("status").Value.Equals("allow")
                        select new DenyFileType()
                        {
                            Name = c.Element("ipaddress").Value,
                            FileTypes = (from f in c.Elements("file") where f.Attribute("status").Value.Equals("deny") select f.Value).ToList()
                        });
            return list.ToList();
        }

        public static void SaveWebsiteDenyFileType(string websiteName, string fileType)
        {
            XDocument data = XDocument.Load(ConfigurationManager.AppSettings["ListDomainIPType"]);
            XElement privacyDomain = data.Descendants("domains").Where(c => c.Element("domain").Value.Equals(websiteName) && c.Element("domain").Attribute("status").Value.Equals("allow")).FirstOrDefault();
            if (privacyDomain != null)
            {
                XElement privacyFile = privacyDomain.Descendants("file").Where(c => c.Value.Equals(fileType)).FirstOrDefault();
                if (privacyFile != null)
                {
                    privacyDomain.Element("file").SetAttributeValue("status", "deny");
                }
                else
                {
                    XElement item = new XElement("file", fileType);
                    item.SetAttributeValue("status", "deny");

                    privacyDomain.Add(item);
                }
            }
            else
            {
                privacyDomain = new XElement("domain", websiteName);
                privacyDomain.SetAttributeValue("status", "allow");
                XElement item = new XElement("domains");
                item.Add(privacyDomain);
                XElement privacyFile = new XElement("file", fileType);
                privacyFile.SetAttributeValue("status", "deny");
                item.Add(privacyFile);
                data.Element("accesscontrols").Add(item);
            }

            data.Save(ConfigurationManager.AppSettings["ListDomainIPType"]);
        }

        public static void DeleteWebsiteDenyFileType(string websiteName, string fileType)
        {
            XDocument data = XDocument.Load(ConfigurationManager.AppSettings["ListDomainIPType"]);

            XElement privacyDomain = data.Descendants("domains").Where(c => c.Element("domain").Value.Equals(websiteName) && c.Element("domain").Attribute("status").Value.Equals("allow")).FirstOrDefault();
            if (privacyDomain != null)
            {
                XElement privacyFile = privacyDomain.Descendants("file").Where(c => c.Value.Equals(fileType)).FirstOrDefault();
                if (privacyFile != null)
                {
                    privacyFile.Remove();
                    data.Save(ConfigurationManager.AppSettings["ListDomainIPType"]);
                }
            }
        }

        public static void DeleteAllWebsiteDenyFileType(string websiteName, string fileType)
        {
            XDocument data = XDocument.Load(ConfigurationManager.AppSettings["ListDomainIPType"]);

            XElement privacyDomain = data.Descendants("domains").Where(c => c.Element("domain").Value.Equals(websiteName) && c.Element("domain").Attribute("status").Value.Equals("allow")).FirstOrDefault();
            if (privacyDomain != null)
            {
                privacyDomain.Remove();
                data.Save(ConfigurationManager.AppSettings["ListDomainIPType"]);
            }
        }
        #endregion

        #region Chain proxy

        public static List<Proxy> GetProxyList()
        {
            XDocument data = XDocument.Load(ConfigurationManager.AppSettings["ProxyData"]);

            var proxies = (from c in data.Descendants("proxy")
                           select new Proxy()
                           {
                               IpAddress = c.Value,
                               Port = c.Attribute("port").Value
                           });
            return proxies.ToList();
        }

        public static void SaveProxyList(Proxy proxy)
        {
            XDocument data = XDocument.Load(ConfigurationManager.AppSettings["ProxyData"]);
            var proxyList = data.Descendants("Proxies");
            var list = (from p in proxyList.Elements("proxy") where p.Value.Equals(proxy.IpAddress) select p).FirstOrDefault();
            if (list != null)
            {
                list.SetValue(proxy.IpAddress);
                list.SetAttributeValue("port", proxy.Port);
            }
            else
            {
                list = new XElement("proxy", proxy.IpAddress);
                list.SetAttributeValue("port", proxy.Port);

                data.Element("Proxies").Add(list);
            }

            data.Save(ConfigurationManager.AppSettings["ProxyData"]);
        }

        public static void DeleteProxy(Proxy proxy)
        {
            XDocument data = XDocument.Load(ConfigurationManager.AppSettings["ProxyData"]);

            XElement oProxy = data.Descendants("proxy").Where(c => c.Value.Equals(proxy.IpAddress)).FirstOrDefault();
            if (oProxy != null)
            {
                oProxy.Remove();
                data.Save(ConfigurationManager.AppSettings["ProxyData"]);
            }
        }

        public static void DeleteAllProxy()
        {
            XDocument data = XDocument.Load(ConfigurationManager.AppSettings["ProxyData"]);

            var proxyList = data.Descendants("proxy");
            if (proxyList != null)
            {
                proxyList.Remove();
                data.Save(ConfigurationManager.AppSettings["ProxyData"]);
            }
        }

        #endregion

    }
}
